/**
 * 公共常用工具函数js文件
 */

/**
 * 跳转至第几页
 */
var gotoPage = function(page, formId) {
	var $form = (formId) ? $(formId) : $('form:first');
	
	$('#page').val(page);
	
	form2cookie($form);
	
	$form.submit();
};

/**
 * form表单值保存到cookie
 */
var form2cookie = function($form) {
	var cookieName = 'query_form';
	var cookieVal = '';
	$form.find('input,select').each(function(){
		var $input = $(this);
		var type = $input.attr('type');
		var name = $input.attr('name');
		var val = $input.val();	
		
		if(type != 'submit' && type != 'button' && type != 'reset')
			cookieVal += name + '=' + val + '&';
		
	});
    
    var options = {'path':'/'};
    
	$.cookie(cookieName, cookieVal, options);
	
	$.cookie('query_form_uri', location.pathname, options);
	
};

/**
 * 初始化查询表单
 * @param formId 表单id
 */
var initQueryForm = function(formId) {
	var $form = (formId) ? $(formId) : $('form:first');
	var query_form_uri = $.cookie('query_form_uri');
	var query_form = $.cookie('query_form');
	var uri = location.pathname;
    
    var options = {'path':'/'};
	
	if(uri != query_form_uri) {
		$.cookie('query_form', '', options);
		$.cookie('query_form_uri', uri, options);
		return;
	}
	
	// 赋值初始化
	var obj = param2Obj(query_form);
	$form.find('input,select').each(function(){
		var $input = $(this);
		var name = $input.attr('name');
		if( obj[name] ) {
			$input.val(obj[name]);
		}
	});
	
};

/**
 * 清除表单cookie
 */
var cleanFormCookie = function() {
    var options = {'path':'/'};
    $.cookie('query_form', null, options);
    $.cookie('query_form_uri', null, options);
};

/**
 * 查询参数串转化成Object
 * @param params id=1&name=cjs&age=26
 * @return obj {id:1, name:'cjs', age:26}
 */
var param2Obj = function(params) {
	var obj = {};
	if( params != null && params != undefined && params != "" ) {
		params = params.replace(/\?/, "");
		var arr = params.split('&');
		for(var index = 0; index < arr.length; index++) {
			var pair = arr[index];
			var indexOf = pair.indexOf('=');
			if(indexOf != -1) {
				var name = pair.substring(0,indexOf);
				var val = "";
				if(indexOf != pair.length-1) {
					val = pair.substring(indexOf+1);
				}
				eval("obj." + name + "='" + val + "';");
			} else if(pair) {
				eval("obj." + pair + "='';");
			}
		}
	}
	return obj;
};
